#!/usr/bin/python
# -*- coding: utf-8 -*-

from django.http import HttpRequest
from django.shortcuts import HttpResponse
from django.template import RequestContext, loader, Context

from wabao.settings import DEBUG
from wabao.utils import json

_template_cache = {} # 进程内的静态变量缓存模板

def render_to_response(template_name, dictionary=None, context_instance=None):
    """封装django的render_to_response, 带cache template的功能，避免频繁调用io,
    当context_instance = request的时候，会使用RequestContext封装一个上下文对象
    典型举例：
    return render_to_response('parent_path/template_name.html', data,
        context_instance=request)
    """
    return HttpResponse(render_to_string(template_name, dictionary, context_instance))

def render_to_string(template_name, dictionary=None, context_instance=None):
    dictionary = dictionary or {}
    if isinstance(template_name, (list, tuple)):
        t = _select_template(template_name)
    else:
        t = _get_template(template_name)
    if isinstance(context_instance, Context):
        context_instance.update(dictionary)
    elif isinstance(context_instance, HttpRequest):
        context_instance = RequestContext(context_instance, dictionary)
    else:
        context_instance = Context(dictionary)
    return t.render(context_instance)

def _select_template(template_name_list):
    "Given a list of template names, returns the first that can be loaded."
    for template_name in template_name_list:
        try:
            return _get_template(template_name)
        except loader.TemplateDoesNotExist:
            continue
        
def _get_template(template_name):
    """try to get template from processer safe cache,
    if not exists, use loader.get_template
    """
    global _template_cache
    t = _template_cache.get(template_name, None)
    if DEBUG or t is None:
        t = loader.get_template(template_name)
        _template_cache[template_name] = t
    return t

def json_response(o):
    """return HttpResponse(json format str)
    
    `o` could be anything we know.
    """
    return HttpResponse(json.dumps(o))